package com.kang.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.Role;
import com.kang.pojo.RoleUser;
import com.kang.pojo.User;
import com.kang.pojo.User_role;
import com.kang.service.JurisdictionService;
import com.kang.service.RoleService;
import com.kang.service.UserService;
import com.vonechina.entity.page.UserPage;

/**
 * 用户管理
 * 
 * @author ysq
 *
 */
@Controller
@RequestMapping("user")
@SessionAttributes({ "userPage" })
public class UserController extends com.kang.controller.Controller {
	/**
	 * 用户管理服务
	 */
	@Resource
	private UserService userService;
	/**
	 * 角色服务
	 */
	@Resource
	private RoleService roles;
	/**
	 * 权限服务
	 */
	@Resource
	private JurisdictionService jss;

	/**
	 * 用于用户登录
	 * 
	 * @param username
	 * @param password
	 * @param session
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toLogin")
	@ResponseBody
	public String selectUser(String username, String password,
			HttpSession session, Model model) throws Exception {
		// request.setCharacterEncoding("utf-8");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", username);
		map.put("password", password);
		User users = null;
		users = userService.selUser(map);// 根据accountName账号password密码查询user用户
		if (users == null) {
			map.put("success", false);
			map.put("errorInfo", "用户名或者密码错误!");
		} else {
			map.put("success", true);
			map.put("userid", users.getUserid());
			session.setAttribute("userName", users.getLoginname());
			session.setAttribute("userID", users.getUserid());
			// List<String> modules = getUserModule(users.getUserid());
			// request.getSession().setAttribute("modules", modules);
			// session.setAttribute("list", modules);
		}
		return JSON.toJSONString(map);
	}

	/**
	 * 根据用户id和用户角色id修改用户信息
	 * 
	 * @param session
	 * @param loginnames
	 * @param rolename
	 * @param userStatus
	 * @param password
	 * @param urid
	 * @param userID
	 * @param accountName
	 * @return
	 */
	@RequestMapping("updateuser2")
	@ResponseBody
	public String updateuser2(HttpSession session, String loginnames,
			int[] rolename, String userStatus, String password, int urid,
			int userID, String accountName) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("编辑用户") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}

		User user1 = new User();
		user1.setLoginname(loginnames);
		user1.setUserid(userID);
		user1.setPassword(password);
		user1.setStatus(userStatus);
		user1.setAccountName(accountName);
		int userCount = userService.updateuser(user1);// 根据userID修改用户user信息

		userService.deleteByuserID(userID);// 根据userID删除角色-权限user_role

		int b = 0;
		for (int i = 0; i < rolename.length; i++) {
			User_role ur = new User_role();
			ur.setUserid(userID);
			ur.setRoleid(rolename[i]);
			ur.setStatus("关闭");
			ur.setCreatedate(new Date());

			b = userService.insert(ur);// 设置添加用户-权限user_role
		}

		if (userCount > 0 & b > 0) {
			result.setResult("success");
		} else {
			result.setResult("fail");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 根据用户id查询出用户信息和关联的角色信息-用于修改编辑用户
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("getUserById")
	@ResponseBody
	public String getUserById(String id) {
		List<Map<?, ?>> userSum = userService.getUserById(id);// 根据用户userID查询出用户user信息和关联的角色信息-用于修改编辑用户
		return JSON.toJSONString(userSum);
	}

	/**
	 * 根据条件查询所有用户
	 * 
	 * @param session
	 * @param model
	 * @param userPage
	 * @return
	 */
	@RequestMapping("selectByWhere")
	public String listUserByPage(HttpSession session, Model model,
			UserPage userPage) {
		initRight(session);
		if (checkRight("查看用户") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("isAdd", checkRight("新增用户") == SUCCESS);
		model.addAttribute("isEdit", checkRight("编辑用户") == SUCCESS);
		model.addAttribute("isDelete", checkRight("删除用户") == SUCCESS);

		List<RoleUser> user = userService.selstcUser(userPage);// 根据UserPage条件查询user用户数据List
		List<Role> role = roles.selectRolename();// 查询角色role
		model.addAttribute("user", user);
		model.addAttribute("role", role);

		userPage.setPageUrl("user/selectByWhere.do");
		model.addAttribute("page", userPage);
		return "system/user/user";
	}

	/**
	 * 检查用户名是否重复
	 * 
	 * @param session
	 * @param request
	 * @param model
	 * @param loginnames
	 * @return
	 */
	@RequestMapping("checkUser")
	@ResponseBody
	public String checkUser(HttpSession session, HttpServletRequest request,
			Model model, String loginnames) {
		AjaxResult result = new AjaxResult();
		int userSum = userService.selUserByLoginName(loginnames);// 根据loginname用户名查询user是否有相同的用户，返回数量
		if (userSum > 0) {
			result.setResult("fail");
		} else {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 检查登录账户是否重复
	 * 
	 * @param session
	 * @param request
	 * @param model
	 * @param accountName
	 * @return
	 */
	@RequestMapping("checkUserAccountName")
	@ResponseBody
	public String checkUserAccountName(HttpSession session,
			HttpServletRequest request, Model model, String accountName) {
		AjaxResult result = new AjaxResult();
		int userSum = userService.selUserByAccountName(accountName);// 根据accountName登录账户查询user是否有相同的用户，返回数量
		if (userSum > 0) {
			result.setResult("fail");
		} else {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 添加用户
	 * 
	 * @param session
	 * @param request
	 * @param model
	 * @param loginnames
	 * @param password
	 * @param rolename
	 * @param userStatus
	 * @param accountName
	 * @return
	 */
	@RequestMapping("adduser2")
	@ResponseBody
	public String addsupplier(HttpSession session, HttpServletRequest request,
			Model model, String loginnames, String password, int[] rolename,
			String userStatus, String accountName) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("新增用户") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		User user = new User();
		user.setLoginname(loginnames);
		user.setPassword(password);
		user.setCreatedate(new Date());
		user.setStatus(userStatus);
		user.setAccountName(accountName);
		int a = userService.adduser(user);// 添加用户user

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", user.getAccountName());
		map.put("password", user.getPassword());
		User users = userService.selUser(map);// 根据accountName账号password密码查询user用户

		int b = 0;
		for (int i = 0; i < rolename.length; i++) {
			User_role ur = new User_role();
			ur.setUserid(users.getUserid());
			ur.setRoleid(rolename[i]);
			ur.setStatus("关闭");
			ur.setCreatedate(new Date());

			b = userService.insert(ur);// 设置添加用户-权限user_role
		}

		if (a > 0 & b > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 根据用户id删除用户
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	@RequestMapping("delectuser2")
	@ResponseBody
	public String delectuser(HttpSession session, int id) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("删除用户") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int usercount = userService.delectuser(id);// 根据用户userID删除user用户

		int user_roleCount = userService.deleteByuserID(id);// 根据userID删除角色-权限user_role

		if (usercount > 0 && user_roleCount > 0) {
			result.setResult("success");
		} else {
			result.setResult("fail");
		}

		return JSON.toJSONString(result);
	}

	/**
	 * 根据用户id修改用户密码
	 * 
	 * @param session
	 * @param oldPaw
	 * @param paw1
	 * @return
	 */
	@RequestMapping("updatePwd")
	@ResponseBody
	public String updatePwd(HttpSession session, String oldPaw, String paw1) {
		initRight(session);
		// 0未知错误，1原密码错误，2修改失败，3修改成功
		int sts = 0;
		List<Map<?, ?>> userSum = userService.getUserById(userID + "");// 根据用户id查询出用户信息和关联的角色信息-用于修改编辑用户
		if (userSum != null && userSum.size() > 0) {
			if (oldPaw.equals(userSum.get(0).get("password").toString().trim())) {
				// 根据userID修改user用户密码
				if (userService.updateUserPwd(userID, paw1) > 0) {
					sts = 3;
				} else {
					sts = 2;
				}

			} else {
				sts = 1;
			}
		}
		return JSON.toJSONString(sts);
	}

}
